package org.erepublik.company.service;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

import org.erepublik.company.EProductType;
import org.erepublik.company.Region;
import org.erepublik.company.searchCriteria.ERawRegion;
import org.erepublik.company.utils.Utils;
import org.json.JSONArray;
import org.json.JSONException;

public class RawRegionsService {

    private HashMap<String, Region> regions = new HashMap<String, Region>();
    
    public RawRegionsService() throws IOException, JSONException {
        InputStream stream = getClass().getClassLoader().getResourceAsStream("regions.json");
        String jsonAsString = Utils.convertStreamToString( stream );

        JSONArray jsonArray = new JSONArray( jsonAsString );
        for (int i=0; i < jsonArray.length(); i++) {
            Region region = Region.getFromJSON( jsonArray.getJSONObject(i) );
            regions.put(region.getName(), region);
        }
    }
    
    
    public Region getRegionByName(String name) {
        return regions.get(name);
    }
    
    
    public static void main(String[] args) {
        try {
            RawRegionsService service = new RawRegionsService();
            System.out.println(service.getRegionByName("Pomerania"));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    public ERawRegion getRawRegion(EProductType productType, String regionName) {
        Region region = regions.get(regionName);
        if (productType == EProductType.OIL)
            return region.getOil();
        if (productType == EProductType.GRAIN)
            return region.getGrain();
        if (productType == EProductType.IRON)
            return region.getIron();
        if (productType == EProductType.STONE)
            return region.getStone();
        if (productType == EProductType.TITANIUM)
            return region.getTitanium();
        
        return null;
    }
    
}
